//
//  FBBooksModel.m
//  FindBook
//
//  Created by tianke on 13-11-1.
//  Copyright (c) 2013年 lzx. All rights reserved.
//

#import "FBBooksModel.h"
#import "FBBooksData.h"
#import "RYCListModelIdentifierPagingPolicy.h"

#define URLSTRING @"http://apis.juhe.cn/goodbook/query?key=b2de0032cf675b92c2cb827c656d68e6&catalog_id=%@&pn=%i&rn=%i"
#define PAGESIZE 20

@implementation FBBooksModel

- (id)initWithDelegate:(id<RYCHTTPRequestModelDelegate>)delegate
{
    self = [super initWithDelegate:delegate];
    if (self) {
        RYCListModelIdentifierPagingPolicy *pagingPolicy = [[RYCListModelIdentifierPagingPolicy alloc] init];
        pagingPolicy.pageSize = PAGESIZE;
        self.pagingPolicy = pagingPolicy;
        
    }
    
    return self;
}

- (ASIHTTPRequest *)request
{
    static int pn = 0;
    if (self.operation == RYCHTTPRequestModelOperation_Refresh) {
        pn = 0;
    }
    else if (self.operation == RYCHTTPRequestModelOperation_Forward)
    {
        pn += PAGESIZE;
    }
    NSString *urlStr = [NSString stringWithFormat:URLSTRING, _catalogID, pn, PAGESIZE, nil];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    RYCFormDataRequest *request = [[RYCFormDataRequest alloc] initWithURL:url];
    
    return request;
}

- (BOOL)handleResponseJSON:(id)aJSON
{
    if ([aJSON isKindOfClass:[NSDictionary class]]) {
        id data = [aJSON objectForKey:@"data"];
        if ([data isKindOfClass:[NSArray class]]) {
           return [super handleResponseJSON:data];
        }
    }
    
    return NO;
}

- (id)parseContent:(NSDictionary *)contentJSON
{
    FBBooksData *bookData = [[FBBooksData alloc] init];
    bookData.title = [contentJSON objectForKey:@"title"];
    bookData.catalog = [contentJSON objectForKey:@"catalog"];
    bookData.tags = [contentJSON objectForKey:@"tags"];
    bookData.sub1 = [contentJSON objectForKey:@"sub1"];
    bookData.sub2 = [contentJSON objectForKey:@"sub2"];
    bookData.img = [contentJSON objectForKey:@"img"];
    bookData.reading = [contentJSON objectForKey:@"reading"];
    bookData.bytime = [contentJSON objectForKey:@"bytime"];
    
    NSArray *online = [[contentJSON objectForKey:@"online"] componentsSeparatedByString:@" "];
    NSMutableArray *onlineArray = [NSMutableArray array];
    for (NSString *string in online) {
        if (string.length > 1) {
            BookOnlineData *onlineData = [BookOnlineData getBookOnlineDataByString:string];
            if (onlineData != nil) {
                [onlineArray addObject:onlineData];
            }
        }
        
    }
    bookData.online = onlineArray;
    
    return bookData;
}

@end
